<?php
namespace app\controller;

use app\BaseController;
use think\Controller;
use think\facade\Db;
use think\facade\View;
use think\captcha\facade\Captcha;
use think\facade\Session;
// 导入 SMS 的 client
use TencentCloud\Sms\V20190711\SmsClient;
// 导入要请求接口对应的 Request 类
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;

class Index extends BaseController
{
    public static function checkIsLogin(){
        if(Session::has('login')){
            if(Session::get('login') != 1){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }
    public static function getUser(){
        if(Session::has('user')){
            return Session::get('user');
        }else{
            return null;
        }
    }
    public static function updateUser(){
        if(Session::has('user')){
            $user = Session::get('user');
            $user = Db::table('user')->where('id', $user['id'])->find();
            Session::set('user', $user);
        }
    }
    /***
     * 用户访问首页
     * @return string
     */
    public function index()
    {
        if($this->checkIsLogin()){
            View::assign('user',$this->getUser());
            return View::fetch('Home/index');
        }else{
            return View::fetch('Login/Login');
        }
    }

    /***
     * 登录页面
     * @return string
     */
    public function login()
    {
        return View::fetch('Login/Login');
    }

    public function out()
    {
        Session::clear();
        return View::fetch('Login/Login');
    }
    /***
     * 用户注册
     * @return string
     */
    public function Register()
    {
        return View::fetch('Register/Register');
    }

    /***
     * 找回密码
     * @return string
     */
    public function FindPW()
    {
        return View::fetch('Login/FindPW');
    }


    public function sendCode($tel){
        try {
            $cred = new Credential("AKIDKOBoAGudy5uTLwlH1IJ6bpmUt3FBrLZ7", "RcV9WcV6VgaCZfY9UbWAWcRzGq88tMY5");
            $httpProfile = new HttpProfile();
            $httpProfile->setReqMethod("GET");  // POST 请求（默认为 POST 请求）
            $httpProfile->setReqTimeout(30);    // 请求超时时间，单位为秒（默认60秒）
            $httpProfile->setEndpoint("sms.tencentcloudapi.com");  // 指定接入地域域名（默认就近接入）
            // 实例化一个 client 选项，可选，无特殊需求时可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法（默认为 HmacSHA256）
            $clientProfile->setHttpProfile($httpProfile);
            // 实例化 SMS 的 client 对象，clientProfile 是可选的
            $client = new SmsClient($cred, "ap-shanghai", $clientProfile);
            // 实例化一个 sms 发送短信请求对象，每个接口都会对应一个 request 对象。
            $req = new SendSmsRequest();
            $req->SmsSdkAppid = "1400219187";
            /* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名，可登录 [短信控制台] 查看签名信息 */
            $req->Sign = "";
            $req->PhoneNumberSet = array("+86".$tel);
            /* 国际/港澳台短信 senderid: 国内短信填空，默认未开通，如需开通请联系 [sms helper] */
            /* 模板 ID: 必须填写已审核通过的模板 ID。可登录 [短信控制台] 查看模板 ID */
            $req->TemplateID = "956097";
            /* 模板参数: 若无模板参数，则设置为空*/

            $num = str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);
            Session::set($tel.'RegCode', $num);
            $req->TemplateParamSet = array($num,"5");
            // 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
            $resp = $client->SendSms($req);
            $resp = $resp->getSendStatusSet();
            $resp = json_encode($resp);
            $de_json = json_decode($resp,TRUE);
            $Code = $de_json[0]['Code'];
            if($Code=='Ok'){
                return show(200, "发送成功", null);
            }else{
                return show(500, "发送失败", $Code);
            }
        }
        catch(TencentCloudSDKException $e) {
            echo $e;
            return show(500, "发送失败", $e);
        }
    }



    /***
     * 个人首页
     * @return string
     */
    public function home()
    {
        if($this->checkIsLogin()){
            View::assign('user',$this->getUser());
            return View::fetch('Home/index');
        }else{
            return View::fetch('Login/Login');
        }
    }

    /***
     * 设置
     * @return string
     */
    public function setting()
    {
        View::assign('user',$this->getUser());
        return View::fetch('User/Setting');
    }

    /***
     * 修改姓名
     * @return string
     */
    public function SettingName()
    {
        View::assign('user',$this->getUser());
        return View::fetch('User/SettingName');
    }


    public function SettingPW()
    {
        View::assign('user',$this->getUser());
        return View::fetch('User/SettingPW');
    }

    public function SettingPayPW()
    {
        View::assign('user',$this->getUser());
        return View::fetch('User/SettingPayPW');
    }


    public function index2()
    {
        $appid = "wx5311e5b71a30b840";
        $secret = "c7c2f847dd1047b195804e3a5b69628a";
        if (session('?userinfo')) {
            if (!isset($_GET['code'])) {//没有code，去微信接口获取code码
                $request = request();
                $callback = $request->url(true);//微信服务器回调url，这里是本页url
                $redirect_uri = urlencode($callback);
                $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
                header("location:$url");
                exit();
            } else {//获取code后跳转回来到这里了
                $code = $_GET['code'];
                $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
                $data_all = $this->get_user_info($data['access_token'], $data['openid']);//获取微信用户信息
                session('userinfo', $data_all);
                $this->checkuser($data_all['openid'], $data_all);
                return json($data_all);
            }
        } else {
            $ret = session('userinfo');
            return json($ret); //返回的获取到的微信用户信息
        }
    }

    /**
     * 3、使用code换取access_token
     * @param string 用于换取access_token的code，微信提供
     * @return array access_token和用户openid数组
     */

    private function get_access_token($code)
    {
        $appid = "wx5311e5b71a30b840";
        $secret = "c7c2f847dd1047b195804e3a5b69628a";
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode . 'msg :' . $user->errmsg;
            exit;
        }
        $data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
        return $data;
    }

    /**
     * 4、使用access_token获取用户信息
     * @param string access_token
     * @param string 用户的openid
     * @return array 用户信息数组
     */

    private function get_user_info($access_token, $openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode . 'msg :' . $user->errmsg;
            exit;
        }
        $data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
        return $data;
    }

    /**
     * 检查用户信息
     * TODO 在这个地方如果在用户表加一个时间字段，就可以每隔多少次对数据库进行一次操作，而不是一直更新操作。
     */

    public function checkuser($openid, $data)
    {
        $user = $this->getUser();
        if(!empty($user['openid'])){//绑定
            $user = $this->getUser();
            $intdata = ['nick' => $data['nickname'], 'head' => $data['headimgurl'], 'openid' => $data['openid'], 'sex' => $data['sex'], 'city' => $data['city'], 'province' => $data['province'], 'creat' => date("Y-m-d H:i:s",time())];
            Db::name('user')->where('id', $user['id'])->update($intdata);
            $this->updateUser();
        }else{//更新
            $user = $this->getUser();
            $intdata = ['nick' => $data['nickname'], 'head' => $data['headimgurl'], 'openid' => $data['openid'], 'sex' => $data['sex'], 'city' => $data['city'], 'province' => $data['province'], 'creat' => date("Y-m-d H:i:s",time())];
            Db::name('user')->where('id', $user['id'])->update($intdata);
            $this->updateUser();
        }
//        if ($check) {
//            /*更新用户信息*/
//            $updata = array();
//            $updata['avatar'] = $data['headimgurl'];
//            $updata['nickname'] = $data['nickname'];
//            Db::name('wxuser')->where('openid', $openid)->update($updata);
//            /*获取最新用户信息并存入缓存*/
//            $newinfo = Db::name('wxuser')->where(array('id' => $check['id']))->find();
//            session('userinfo', $newinfo);
//        } else {
//            /*新增用户信息*/
//            $intdata = array();
//            $intdata = ['nickname' => $data['nickname'], 'avatar' => $data['headimgurl'], 'openid' => $data['openid'], 'gender' => $data['sex'], 'city' => $data['city'], 'province' => $data['province'], 'county' => $data['country'], 'create_time' => time()];
//            Db::name('wxuser')->insert($intdata);
//            $userId = Db::name('wxuser')->getLastInsID();
//            /*获取最新用户信息并存入缓存*/
//            if (!session('?userinfo')) {
//                $newinfo = Db::name('wxuser')->where(array('id' => $userId))->find();
//                session('userinfo', $newinfo);
//            }
//        }
    }


    /***
     * 生成验证码
     * @return \think\Response
     */
    public function captcha()
    {
        ob_clean();
        return Captcha::create();
    }
}
